package com.echo.servlet.UserServlet;

import com.echo.entity.User;
import com.echo.service.UserService;
import com.echo.servlet.BaseServlet;
import com.echo.util.BusinessException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet({"/register", "/echo-network/register"}) // 与前端表单action对应
public class RegisterServlet extends BaseServlet {

    private static final Logger logger = Logger.getLogger(RegisterServlet.class.getName());
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("===== 开始处理注册请求 ====");
        
        // 设置编码（解决中文乱码）
        setRequestEncoding(request);
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        String confirmPwd = request.getParameter("confirmPwd");
        String email = request.getParameter("email");
        String nickname = request.getParameter("nickname");
        
        logger.info("接收到注册参数 - username: " + username + ", email: " + email);

        // 封装User对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 暂存明文，Service层加密
        user.setEmail(email);
        user.setNickname(nickname);
        
        logger.info("用户对象创建完成: " + user.toString());

        // 调用Service注册，处理结果
        try {
            logger.info("准备调用UserService.register()方法");
            userService.register(user, confirmPwd);
            logger.info("用户注册成功！即将重定向到登录页面");
            // 注册成功：重定向到登录页，并带上成功提示参数
            response.sendRedirect(request.getContextPath() + "/login.html?registerSuccess=true");
        } catch (BusinessException e) {
            logger.log(Level.SEVERE, "注册失败: " + e.getMessage(), e);
            // 注册失败：存储错误信息，转发回注册页
            request.setAttribute("errorMsg", e.getMessage());
            forward(request, response, "/register.html");
        }
        
        logger.info("===== 注册请求处理完成 ====");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}